import os
import unittest
from unittest.mock import patch, mock_open
from main import process_files

class TestProcessFiles(unittest.TestCase):
    def setUp(self):
        # 创建测试环境
        self.input_dir = 'D:\03-code\pycharm\aigc\openaidemo\tmp'
        self.output_dir = 'D:\03-code\pycharm\aigc\openaidemo\tmp'
        self.test_file = '1.txt'
        self.test_content = 'hello world\nthis is a test.'
        # 创建输入文件
        with open(os.path.join(self.input_dir, self.test_file), 'w') as file:
            file.write(self.test_content)
        # 创建输出目录
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

    def tearDown(self):
        # 清理测试环境
        os.remove(os.path.join(self.input_dir, self.test_file))
        if os.path.exists(self.output_dir):
            for file in os.listdir(self.output_dir):
                os.remove(os.path.join(self.output_dir, file))
            os.rmdir(self.output_dir)

    @patch('main.open', new_callable=mock_open, read_data='mocked content')
    def test_process_files(self, mock_file):
        # 测试文件处理功能
        process_files(self.input_dir, self.output_dir)
        # 检查是否正确地创建了输出文件
        output_file = f"upper_{self.test_file}"
        output_path = os.path.join(self.output_dir, output_file)
        self.assertTrue(os.path.exists(output_path))
        
        # 检查输出文件内容是否为预期的大写内容
        with open(output_path, 'r') as file:
            content = file.read()
        expected_content = self.test_content.upper()
        self.assertEqual(content, expected_content)
        
        # 检查是否使用了mock_open
        mock_file.assert_called_once_with(os.path.join(self.input_dir, self.test_file), 'r', encoding='utf-8')

    def test_output_directory_creation(self):
        # 测试输出目录是否在不存在时被创建
        non_existent_output_dir = 'non_existent_dir'
        process_files(self.input_dir, non_existent_output_dir)
        self.assertTrue(os.path.exists(non_existent_output_dir))

if __name__ == '__main__':
    unittest.main()